from openai import OpenAI
import os
from dotenv import load_dotenv

# 加载 .env 文件（注意原始字符串标记 r）
load_dotenv(dotenv_path=r'D:\桌面\Project\PythonProject2\.env')

# 初始化客户端（确保 base_url 包含 /v1）
client = OpenAI(
    api_key=os.environ.get('DEEPSEEK_API_KEY'),
    base_url="https://api.deepseek.com/v1"
)

# 第一轮对话
messages = [{"role": "user", "content": "给我背诵一下出师表"}]
print("第一轮提问:", messages[0]["content"])

response = client.chat.completions.create(
    model="deepseek-reasoner",
    messages=messages,
    stream=True
)

reasoning_content = ""
content = ""

for chunk in response:
    delta = chunk.choices[0].delta
    # 处理推理过程（判断非None）
    if hasattr(delta, 'reasoning_content') and delta.reasoning_content is not None:
        reasoning_content += delta.reasoning_content
    # 处理回答内容（核心修正：跳过 None）
    if delta.content is not None:
        content += delta.content

print("\n模型推理过程:", reasoning_content)
print("第一轮回答:", content)
messages.append({"role": "assistant", "content": content})

# 第二轮对话
second_question = "给我背诵一下静夜思'?"
messages.append({"role": "user", "content": second_question})
print("\n第二轮提问:", second_question)

response = client.chat.completions.create(
    model="deepseek-reasoner",
    messages=messages,
    stream=True
)

# 第二轮对话的流式处理（添加实时打印）
reasoning_content = ""
content = ""

print("\n第二轮回答（实时输出）: ", end='', flush=True)  # 实时换行，实时拼接
for chunk in response:
    delta = chunk.choices[0].delta
    if hasattr(delta, 'reasoning_content') and delta.reasoning_content is not None:
        reasoning_content += delta.reasoning_content
    if delta.content is not None:
        content += delta.content
        print(delta.content, end='', flush=True)  # 实时打印当前chunk的内容

print("\n\n模型推理过程:", reasoning_content)
print("第二轮回答（完整）:", content)
messages.append({"role": "assistant", "content": content})